package com.xin.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.xin.entity.crm.EmployEntity;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

/**
 * @author admin
 */
public class JWTUtils {

    /**
     * 获取token
     * @param u user
     * @return token
     */
    public static String getToken(EmployEntity u) {
        Calendar instance = Calendar.getInstance();
        //默认令牌过期时间7天
        instance.add(Calendar.DATE, 7);

        JWTCreator.Builder builder = JWT.create();
        builder.withClaim("username", u.getUsername())
                .withClaim("password", u.getPassword());
       return builder.withExpiresAt(instance.getTime()).sign(Algorithm.HMAC256(u.getPassword()));
    }

    /**
     * 验证token合法性 成功返回token
     */
    public static DecodedJWT verify(String token) throws InterruptedException {
        if (token==null||token.trim().equals("")) throw new InterruptedException("token不能为空");

        //获取登录用户真正的密码假如数据库查出来的是123456
        String password = "admin";
        JWTVerifier build = JWT.require(Algorithm.HMAC256(password)).build();
        return build.verify(token);
    }

    public static Map<String ,String > getUserInfo(DecodedJWT decodedJWT){
        String userAccount = decodedJWT.getClaim("username").asString();
        String userPassword = decodedJWT.getClaim("password").asString();
        Map<String ,String> map = new HashMap(){
            private static final long serialVersionUID = 9068615210217131466L;
            {put("username",userAccount);put("password",userPassword);}};
        return map;
    }

}
